package cn.bdqn.service.Role;

import cn.bdqn.dao.Role.RoleMapper;
import cn.bdqn.dao.Role.User_RoleMapper;
import cn.bdqn.pojo.Role.SysRole;
import cn.bdqn.pojo.Role.SysUserRole;
import cn.bdqn.utils.Json;
import cn.bdqn.utils.RedisCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

import static cn.bdqn.utils.RedisConstants.REDIS_ROLE_KEY;

@Service
@Slf4j
public class RoleService{
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    User_RoleMapper userRoleMapper;
    @Autowired
    private RedisCache redisCache;
    /**
     * 添加角色表与用户表  中间表的数据
     * @param userRole  类中的userid为必传
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer insertUserAndRole(SysUserRole userRole)
    {
        int insert = userRoleMapper.insert(userRole);
        redisCache.deleteObject(REDIS_ROLE_KEY);  //将存入redis 的角色数据删除;  下面方法会重新加载 角色表 填入redis中
        return insert;


    }

    /**
     * 查询数据库的 角色表
     * @return
     */
    public Json getAllAdmiRole() {
        List<SysRole> sysRoles = redisCache.getCacheObject(REDIS_ROLE_KEY);
        if (Objects.nonNull(sysRoles)){
            return Json.ok(sysRoles);
        }
        log.info("查询了数据库");
        sysRoles = roleMapper.selectList(new QueryWrapper<SysRole>().ge("role_id",1000));
        if (Objects.isNull(sysRoles)){
            throw new RuntimeException("系统异常,请检查数据库");
        }
        redisCache.setCacheObject(REDIS_ROLE_KEY,sysRoles);
        return Json.ok(sysRoles);
    }

    /**
     * 修改管理员的角色信息
     * @param userid
     * @param roleid
     * @return
     */
    public Json updateRoleByAdmin(Integer userid, Integer roleid) {
        Boolean aBoolean = userRoleMapper.updateRoelByAdmin(userid, roleid);
        if (aBoolean == true){
            return Json.ok();
        }
        return Json.fall("修改失败");
    }
}
